"use strict";
var C = Object.create;
var i = Object.defineProperty;
var U = Object.getOwnPropertyDescriptor;
var E = Object.getOwnPropertyNames;
var F = Object.getPrototypeOf,
  R = Object.prototype.hasOwnProperty;
var D = (t, r) => {
    for (var n in r) i(t, n, { get: r[n], enumerable: !0 });
  },
  h = (t, r, n, a) => {
    if ((r && typeof r == "object") || typeof r == "function")
      for (let o of E(r))
        !R.call(t, o) &&
          o !== n &&
          i(t, o, {
            get: () => r[o],
            enumerable: !(a = U(r, o)) || a.enumerable,
          });
    return t;
  };
var v = (t, r, n) => (
    (n = t != null ? C(F(t)) : {}),
    h(
      r || !t || !t.__esModule
        ? i(n, "default", { value: t, enumerable: !0 })
        : n,
      t
    )
  ),
  T = (t) => h(i({}, "__esModule", { value: !0 }), t);
var A = {};
D(A, { activate: () => S, deactivate: () => W });
module.exports = T(A);
var m = v(require("vscode"));
var s = require("vscode"),
  w = class {
    statusBarItem;
    constructor() {
      (this.statusBarItem = s.window.createStatusBarItem(
        s.StatusBarAlignment.Right,
        200
      )),
        (this.statusBarItem.text = "\u272A\u2654Browser"),
        (this.statusBarItem.color = "yellow"),
        (this.statusBarItem.name = "browserStateBar"),
        (this.statusBarItem.command = "vscodeBrowser.stateBarBrowser"),
        (this.statusBarItem.tooltip = "please click to open browser"),
        this.statusBarItem.show();
    }
    async update() {
      this.statusBarItem &&
        s.window.showInformationMessage("Browser State Bar Updated");
    }
  },
  g = new w();
var e = v(require("vscode"));
function c(t, r) {
  return e.workspace.getConfiguration().get(t, r);
}
function P(t) {
  return {
    extensionPath: t.extensionPath,
    quality: c("VscodeBrowser.quality", 100),
    chromeExecutable: c("VscodeBrowser.chromeExecutable"),
    startUrl: c("VscodeBrowser.startUrl", "https://bilibili.com"),
    proxy: c("VscodeBrowser.proxy", ""),
  };
}
async function l(t, r) {
  let n = P(t);
  r = r ?? n.startUrl;
  let a = e.window.createWebviewPanel(
    "browser",
    "index.tsx",
    e.ViewColumn.Two,
    {
      enableScripts: !0,
      enableCommandUris: !0,
      retainContextWhenHidden: !0,
      enableFindWidget: !0,
      localResourceRoots: [e.Uri.file(n.extensionPath)],
    }
  );
  (a.webview.html = await d(r)),
    a.webview.onDidReceiveMessage(
      async (o) => {
        switch (o.command) {
          case "loadUrl":
            let u = await f(o.url);
            a.webview.html = await d(o.url, u);
            break;
          case "alert":
            e.window.showInformationMessage(o.text);
            break;
          case "urlChanged":
            let p = o.url;
            (u = await f(p)),
              (a.webview.html = await d(p, u)),
              e.window.showInformationMessage("url changed to " + o.url);
            break;
          case "openFile":
            let b = e.Uri.parse(o.path),
              x = await e.workspace.openTextDocument(b);
            (await e.window.showTextDocument(x)).revealRange(
              new e.Range(new e.Position(0, 0), new e.Position(0, 0))
            );
            break;
          case "openFolder":
            let B = e.Uri.parse(o.path);
            await e.commands.executeCommand("vscode.openFolder", B);
            break;
          case "openWorkspace":
            let y = e.Uri.parse(o.path);
            await e.commands.executeCommand("vscode.openWorkspace", y);
            break;
          case "openTerminal":
            e.window.createTerminal().sendText(o.path);
            break;
          case "openCommand":
            await e.commands.executeCommand(o.commandId, o.args);
            break;
          case "openUrl":
            e.env.openExternal(e.Uri.parse(o.url));
            break;
          case "reload":
            a.webview.html = await d(r);
            break;
          case "openPreview":
            let k = e.Uri.parse(o.path),
              I = await e.workspace.openTextDocument(k);
            (await e.window.showTextDocument(I, { preview: !0 })).revealRange(
              new e.Range(new e.Position(0, 0), new e.Position(0, 0))
            );
            break;
          case "openSettings":
            await e.commands.executeCommand("workbench.action.openSettings");
            break;
          case "openExtensions":
            await e.commands.executeCommand(
              "workbench.extensions.action.showExtensionsAssistant"
            );
            break;
          default:
            break;
        }
      },
      void 0,
      t.subscriptions
    );
}
async function f(t) {
  try {
    return t
      ? await (await fetch(t)).text()
      : `<p>Error loading ${t}: No URL provided</p>`;
  } catch (r) {
    return `<p>Error loading ${t}: ${r}</p>`;
  }
}
async function d(t, r = "") {
  return `
        <!DOCTYPE html>
        <html lang="en">
        <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>Index.tsx</title>
            <style>
				 body { margin: 0; font-family: Arial, sans-serif  ; margin:0 ; padding:0 ; overflow:hidden; display :flex ;    flex-direction: column;   height :100vh } 
             iframe { width: 375px; height: 667px; margin :0; border: none: 
			 padding:0;    } 
			   
			 
			   .toolbar {
			    display: flex; 
            align-items: center;
            background-color: #32485b;
            
        }
        .refresh  , .leftArrow, .rightArrow {
		      margin-left : 3px;
            margin-right: 3px;
            background: none;
            border: none;
            cursor: pointer;
            color: white;
            font-size: 1.5em;
			    margin-top:10px;
      &:hover {
              opacity: 0.7;
                         
      }
        }
        .urlbar {
           box-sizing: border-box; /* \u786E\u4FDD padding \u548C border \u5305\u542B\u5728\u5BBD\u5EA6\u5185 */
            padding: 8px;
            flex:1 ;
               align-items: center;
               width :300px ;
            margin-left: 60px     !important;
            margin-bottom: 5px   !important;
            margin-top: 5px      !important;
            border: none;
            border-radius: 4px;
            font-size: 1em;
            background-color: inherit;
            color: white;
			
        }
            </style>
			<link  rel="stylesheet"  href="./toolsBar.css"> 
        </head>
        <body>
		<div class="toolbar">
        <div class="inner"  onclick="returnBack()">
       
        <button  class="rightArrow" onclick="returnForward()">
         <svg width="1em" height="1em" viewBox="0 0 32 32" ><path d="M18 6l-1.43 1.393L24.15 15H4v2h20.15l-7.58 7.573L18 26l10-10L18 6z" fill="currentColor"></path></svg>
        </button>
          <button
            class="refresh"
            onClick="pageRefresh()"
          >
            <svg width="1em" height="1em" viewBox="0 0 32 32" >
      <path d="M12 10H6.78A11 11 0 0 1 27 16h2A13 13 0 0 0 6 7.68V4H4v8h8z" fill="currentColor"></path>
      <path d="M20 22h5.22A11 11 0 0 1 5 16H3a13 13 0 0 0 23 8.32V28h2v-8h-8z" fill="currentColor"></path>
      </svg>
          </button>
          <input
          class="urlbar"
          type="text"
          value="http://m.music.csair.com"
          onchange="handleInput(event)"
          onKeyDown="handleKeyDown(event)"
        />
        </div>
      </div>
      </div>
             <iframe  src=${t}  id="myFrameId"  loading="lazy"  allowfullscreen
			 >
			 </iframe> 
			 <div>${r}</div>
        </body>   
		<script> 
    function checkUrlResult() {
         const iframe = document.getElementById('myFrameId');

          iframe.onload = function() {
                console.log('Iframe content loaded successfully.');
                return true ; 
            };

            // \u76D1\u542C onerror \u4E8B\u4EF6
            iframe.onerror = function() {
                iframe.contentDocument.open();
                iframe.contentDocument.write(\`${r
                  .replace(/`/g, "\\`")
                  .replace(/\$/g, "\\$")}\`);
                iframe.contentDocument.close();
                console.error('Error loading iframe content.'); 
                return false ; 

            }; 
}
  checkUrlResult() ; 
          function handleKeyDown(event) {
                if (event.keyCode === 13) {
                  let url = event.target.value.trim();  
				  if(!url.startsWith('http://') && !url.startsWith('https://')) {
                    url = 'http://' + url; 
                    if(!url.endsWith('.com') && !url.includes('localhost') &&!url.includes('127.0.0.1'))  {url += '.com';    }
                  } 
                    checkUrlResult() ;  
                    event.target.value = url; 
                  document.getElementById('myFrameId').src = url;
                  vscode.postMessage({ command: 'urlChanged', url: url });
  			   }
           }

        // Function to navigate to the URL in the address bar
        // function navigate() {
        //   const url = addressBar.value;
        //   contentFrame.src = url;
        //   vscode.postMessage({ command: 'urlChanged', url: url });
        // }

        // Function to refresh the page 
		  function  pageRefresh() { 
		   document.getElementsById('myFrameId').src = document.getElementsById('myFrameId').src;
		  }

        // Handle messages from the extension
        // window.addEventListener('message', (event) => {
        //   const message = event.data;
        //   if (message.command === 'setUrl') {
        //     addressBar.value = message.url;
        //     contentFrame.src = message.url;
        //   }
        // });
        function returnBack() { 
          document.getElementsById('myFrameId').src = document.getElementsById('myFrameId').src;
        } 
		 </script>
        </html>
    `;
}
function S(t) {
  let r = m.commands.registerCommand(
      "vscodeBrowser.stateBarBrowser",
      async (o) => (g.update(), await l(t, o))
    ),
    n = m.commands.registerCommand(
      "vscodeBrowser.openInBrowser",
      async (o) => await l(t, o)
    ),
    a = m.commands.registerCommand(
      "vscodeBrowser.clickBrowserIcon",
      async (o) => await l(t, o)
    );
  t.subscriptions.push(n, a, r);
}
function W() {}
0 && (module.exports = { activate, deactivate });
